const express = require('express')()
var http = require('http').Server(express);
const bodyParser=require('body-parser');
var io = require('socket.io')(http);
var jsonParser = bodyParser.json();
const electron = require('electron');
const ipcMain = require('electron').ipcMain;
const portIsOccupied = require('./src/lib/portIsOccupied')
let port = 2000;

ipcMain.on('get-express-port', function(event) {
    event.returnValue = port;
});




const app = electron.app;
require('./src/lib/Date')

var dateTime = new Date();



io.on('connection', function(socket){
    console.log('a user connected');
    socket.on('disconnect', function(){
        console.log('user disconnected'.red);
    });
});
express.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();
});
express.post('/tojson', jsonParser ,(req, res) => {
    dateTime = new Date()
    io.emit('data:update', {
        content:req.body,
        date:dateTime.format('yyyy-MM-dd HH:mm:ss')
    })
    res.send({status:0})
})

portIsOccupied(port)
    .then(_port=>{
        http.listen(_port, () => console.log(`Example app listening on port ${_port}!`))
    })



app.on('ready', ()=>{

    let win = new electron.BrowserWindow({
        width: 496,
        height: 483,
        webPreferences: {
            nodeIntegration: true
        },
        frame:true,
        resizable:true,
        icon:'./favicon.ico'
    })

    electron.Menu.setApplicationMenu(null)

    win.loadFile('./src/index.html')
    win.webContents.openDevTools({
        mode:'bottom'
    })

})






